package com.yb.guigu.pick.auth.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yb.guigu.pick.auth.bean.dto.request.SysUserAddInfo;
import com.yb.guigu.pick.auth.entity.SysRole;
import com.yb.guigu.pick.auth.entity.SysUser;
import com.yb.guigu.pick.auth.entity.SysUserRole;
import com.yb.guigu.pick.auth.mapper.SysRoleMapper;
import com.yb.guigu.pick.auth.mapper.SysUserRoleMapper;
import com.yb.guigu.pick.core.bean.event.GuiguPickEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/6/9 15:27
 * FileName: SysUserListener
 * Description:
 */

@Component
@Slf4j
public class SysUserListener {


    @Autowired
    SysRoleMapper sysRoleMapper;


    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @EventListener
    @Async
    public void handle(GuiguPickEvent<SysUserAddInfo> event){
        log.info("accept event:{}",event);
        SysUserAddInfo sysUserAddInfo = event.getData();
        SysUser sysUser = sysUserAddInfo.getSysUser();

        SysRole anonymousRole = getAnonymousRole();
        SysUserRole sysUserRole=new SysUserRole();
        sysUserRole.setUserId(sysUser.getUserId());
        sysUserRole.setRoleId(anonymousRole.getRoleId());
        sysUserRoleMapper.insert(sysUserRole);

        log.info("event {} processed",event);
    }


    private SysRole getAnonymousRole(){

        return sysRoleMapper.selectOne(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleCode, "anonymous")
                .select(SysRole::getId, SysRole::getRoleId));
    }
}
